<template>
  <div class="content-test-container">
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <span>内容渲染测试</span>
          <el-button type="primary" @click="refreshTest">刷新测试</el-button>
        </div>
      </template>

      <!-- 测试步骤说明 -->
      <div class="test-steps">
        <h3>测试步骤：</h3>
        <ol>
          <li>在下方编辑器中创建富文本内容</li>
          <li>点击"保存内容"按钮</li>
          <li>复制生成的小程序预览链接</li>
          <li>在微信开发者工具中打开小程序并访问该链接</li>
          <li>验证内容是否正确渲染</li>
        </ol>
      </div>

      <!-- 编辑器区域 -->
      <div class="editor-section">
        <h3>内容编辑器：</h3>
        <QuillEditor
          ref="quillEditorRef"
          v-model:content="testContent"
          :options="editorOptions"
          content-type="html"
          style="height: 400px; margin-bottom: 20px;"
        />
      </div>

      <!-- 操作按钮 -->
      <div class="actions">
        <el-button @click="setTestContent">设置测试内容</el-button>
        <el-button @click="clearContent">清空内容</el-button>
        <el-button type="primary" @click="saveContent" :loading="saving">保存内容</el-button>
        <el-button @click="previewContent">预览HTML</el-button>
      </div>

      <!-- 保存结果 -->
      <div v-if="saveResult" class="save-result">
        <h3>保存结果：</h3>
        <div class="result-info">
          <p><strong>项目ID：</strong>{{ saveResult.id }}</p>
          <p><strong>项目名称：</strong>{{ saveResult.name }}</p>
          <p><strong>内容类型：</strong>{{ saveResult.content_type }}</p>
          <p><strong>内容长度：</strong>{{ saveResult.content?.length || 0 }} 字符</p>
        </div>
        
        <!-- 小程序预览链接 -->
        <div class="preview-links">
          <h4>小程序预览链接：</h4>
          <div class="link-item">
            <el-input
              v-model="miniProgramLink"
              readonly
              placeholder="小程序链接将在这里显示"
            >
              <template #append>
                <el-button @click="copyLink">复制链接</el-button>
              </template>
            </el-input>
          </div>
        </div>
      </div>

      <!-- HTML预览 -->
      <div v-if="showPreview" class="html-preview">
        <h3>HTML预览：</h3>
        <div class="preview-content" v-html="processedContent"></div>
        <div class="raw-html">
          <h4>原始HTML：</h4>
          <pre>{{ processedContent }}</pre>
        </div>
      </div>

      <!-- 调试信息 -->
      <div class="debug-info">
        <h3>调试信息：</h3>
        <div v-for="(log, index) in debugLogs" :key="index" class="debug-log">
          {{ log }}
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import QuillEditor from '@/components/QuillEditor.vue'
import axios from 'axios'

// 响应式数据
const testContent = ref('')
const saving = ref(false)
const saveResult = ref(null)
const showPreview = ref(false)
const debugLogs = ref([])

// 编辑器引用
const quillEditorRef = ref(null)

// 编辑器配置
const editorOptions = {
  theme: 'snow',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ 'header': 1 }, { 'header': 2 }],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      [{ 'script': 'sub'}, { 'script': 'super' }],
      [{ 'indent': '-1'}, { 'indent': '+1' }],
      [{ 'direction': 'rtl' }],
      [{ 'size': ['small', false, 'large', 'huge'] }],
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'color': [] }, { 'background': [] }],
      [{ 'font': [] }],
      [{ 'align': [] }],
      ['clean'],
      ['link', 'image']
    ]
  },
  placeholder: '请输入测试内容...'
}

// 计算属性
const processedContent = computed(() => {
  if (!testContent.value) return ''
  
  // 获取编辑器处理后的HTML内容
  if (quillEditorRef.value && quillEditorRef.value.getContent) {
    const content = quillEditorRef.value.getContent()
    return content.html || testContent.value
  }
  
  return testContent.value
})

const miniProgramLink = computed(() => {
  if (!saveResult.value) return ''
  return `pages/rich-text/rich-text?itemId=${saveResult.value.id}`
})

/**
 * 添加调试日志
 * @param {string} message - 日志信息
 */
const addDebugLog = (message) => {
  const timestamp = new Date().toLocaleTimeString()
  debugLogs.value.unshift(`[${timestamp}] ${message}`)
  // 只保留最近20条日志
  if (debugLogs.value.length > 20) {
    debugLogs.value = debugLogs.value.slice(0, 20)
  }
}

/**
 * 设置测试内容
 */
const setTestContent = () => {
  const sampleContent = `
    <h1>富文本内容测试</h1>
    <p>这是一个<strong>富文本内容</strong>的测试页面。</p>
    
    <h2>代码块测试</h2>
    <pre class="ql-syntax code-default">console.log('Hello World!');</pre>
    
    <h2>样式测试</h2>
    <p>这里有<em>斜体文字</em>和<u>下划线文字</u>。</p>
    <p style="color: red;">这是红色文字</p>
    <p style="background-color: yellow;">这是黄色背景</p>
    
    <h2>列表测试</h2>
    <ul>
      <li>列表项目1</li>
      <li>列表项目2</li>
      <li>列表项目3</li>
    </ul>
    
    <h2>引用测试</h2>
    <blockquote>这是一个引用块的内容。</blockquote>
  `
  
  testContent.value = sampleContent
  addDebugLog('设置测试内容完成')
}

/**
 * 清空内容
 */
const clearContent = () => {
  testContent.value = ''
  saveResult.value = null
  showPreview.value = false
  addDebugLog('内容已清空')
}

/**
 * 保存内容到后端
 */
const saveContent = async () => {
  if (!testContent.value.trim()) {
    ElMessage.warning('请先输入内容')
    return
  }
  
  try {
    saving.value = true
    addDebugLog('开始保存内容...')
    
    // 获取处理后的HTML内容
    const htmlContent = processedContent.value
    
    // 构造保存数据
    const saveData = {
      name: `测试内容_${new Date().toLocaleString()}`,
      content: htmlContent,
      content_type: 'rich_text',
      category_id: 1, // 假设分类ID为1
      description: '这是一个内容渲染测试项目'
    }
    
    addDebugLog(`准备保存数据: ${JSON.stringify(saveData, null, 2)}`)
    
    // 发送保存请求
    const response = await axios.post('http://localhost:8081/api/v1/items', saveData)
    
    if (response.data && response.data.code === 200) {
      saveResult.value = response.data.data
      addDebugLog('内容保存成功')
      ElMessage.success('内容保存成功！')
    } else {
      throw new Error(response.data?.message || '保存失败')
    }
    
  } catch (error) {
    console.error('保存内容失败:', error)
    addDebugLog(`保存失败: ${error.message}`)
    ElMessage.error(`保存失败: ${error.message}`)
  } finally {
    saving.value = false
  }
}

/**
 * 预览内容
 */
const previewContent = () => {
  if (!testContent.value.trim()) {
    ElMessage.warning('请先输入内容')
    return
  }
  
  showPreview.value = !showPreview.value
  addDebugLog(`预览模式: ${showPreview.value ? '开启' : '关闭'}`)
}

/**
 * 复制链接
 */
const copyLink = async () => {
  if (!miniProgramLink.value) {
    ElMessage.warning('没有可复制的链接')
    return
  }
  
  try {
    await navigator.clipboard.writeText(miniProgramLink.value)
    ElMessage.success('链接已复制到剪贴板')
    addDebugLog('链接复制成功')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败，请手动复制')
  }
}

/**
 * 刷新测试
 */
const refreshTest = () => {
  clearContent()
  debugLogs.value = []
  addDebugLog('测试环境已刷新')
}

// 初始化
addDebugLog('内容测试页面已加载')
</script>

<style scoped>
.content-test-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.test-steps {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.test-steps h3 {
  margin-top: 0;
  color: #409eff;
}

.test-steps ol {
  margin: 10px 0;
  padding-left: 20px;
}

.test-steps li {
  margin: 8px 0;
  line-height: 1.6;
}

.editor-section {
  margin-bottom: 30px;
}

.editor-section h3 {
  margin-bottom: 15px;
  color: #303133;
}

.actions {
  margin-bottom: 30px;
  text-align: center;
}

.actions .el-button {
  margin: 0 8px;
}

.save-result {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 8px;
}

.save-result h3 {
  margin-top: 0;
  color: #409eff;
}

.result-info {
  margin-bottom: 20px;
}

.result-info p {
  margin: 8px 0;
  font-family: monospace;
}

.preview-links {
  margin-top: 20px;
}

.preview-links h4 {
  margin-bottom: 10px;
  color: #67c23a;
}

.link-item {
  margin-bottom: 10px;
}

.html-preview {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
}

.html-preview h3 {
  margin-top: 0;
  color: #303133;
}

.preview-content {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  min-height: 100px;
}

.raw-html {
  margin-top: 20px;
}

.raw-html h4 {
  margin-bottom: 10px;
  color: #909399;
}

.raw-html pre {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-all;
  font-size: 12px;
  line-height: 1.4;
  max-height: 300px;
  overflow-y: auto;
}

.debug-info {
  padding: 20px;
  background-color: #fafafa;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  max-height: 400px;
  overflow-y: auto;
}

.debug-info h3 {
  margin-top: 0;
  color: #909399;
}

.debug-log {
  font-family: monospace;
  font-size: 12px;
  padding: 4px 0;
  border-bottom: 1px solid #f0f0f0;
  color: #666;
}

.debug-log:last-child {
  border-bottom: none;
}
</style>